/* Source: http://robotics.umr.edu/trac/browser/lua/ben/timer_native.c */

#include <time.h>
#include <sys/time.h>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include "lua_native_timer.h"

static int delay(lua_State *L)
{
	lua_Integer msec;
	struct timeval tm;

	msec = luaL_checkinteger(L, 1);
	if(msec <= 0) return 0;

	tm.tv_sec = msec/1000;
	/*tm.tv_nsec = (msec%1000)*1000000;*/ /*TODO: Fix */
    #define BAD_MANNING
    #ifndef BAD_MANNING
	nanosleep(&tm, NULL);
	#else
        #warning BAD MANNING!
    #endif
	return 0;
}

static int get_time(lua_State *L)
{
	struct timeval tv;

	gettimeofday(&tv, NULL);
	lua_createtable(L, 0, 2);

	lua_pushinteger(L, (lua_Integer) tv.tv_sec);
	lua_setfield(L, -2, "sec");
	lua_pushinteger(L, (lua_Integer) tv.tv_usec);
	lua_setfield(L, -2, "usec");

	return 1;
}

static int microtime(lua_State *L)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);

    double microtime = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0f;

    lua_pushnumber(L, microtime);

    return 1;
}

static const luaL_Reg timer_lib[] =
{
	{ "delay", delay },
	{ "get_time", get_time },
	{ "microtime", microtime },
	{ NULL, NULL }
};

LUALIB_API int luaopen_timer_native(lua_State *L)
{
	luaL_register(L, "timer", timer_lib);

	return 1;
}
